<template>
	<view class="container">
		<!-- 头部标题 -->
		<view class="header">
			<text class="title">统计分析</text>
		</view>
		
		<!-- 时间筛选 -->
		<view class="filter-bar">
			<view class="time-filter">
				<view 
					v-for="(item, index) in timeRanges" 
					:key="index" 
					:class="['time-item', activeTimeRange === item.id ? 'active' : '']"
					@click="changeTimeRange(item.id)"
				>
					<text>{{ item.name }}</text>
				</view>
			</view>
			<view class="custom-date" @click="showDatePicker = true">
				<text>自定义</text>
				<text class="date-icon">▼</text>
			</view>
		</view>
		
		<!-- 数据概览卡片 -->
		<view class="data-cards">
			<view class="data-card">
				<view class="card-title">设备数据</view>
				<view class="card-content">
					<view class="data-item">
						<text class="data-value">{{ stats.totalDevices }}</text>
						<text class="data-label">设备总数</text>
					</view>
					<view class="data-item">
						<text class="data-value">{{ stats.onlineDevices }}</text>
						<text class="data-label">在线设备</text>
					</view>
					<view class="data-item">
						<text class="data-value">{{ stats.offlineDevices }}</text>
						<text class="data-label">离线设备</text>
					</view>
				</view>
			</view>
			
			<view class="data-card">
				<view class="card-title">告警数据</view>
				<view class="card-content">
					<view class="data-item">
						<text class="data-value">{{ stats.totalAlarms }}</text>
						<text class="data-label">告警总数</text>
					</view>
					<view class="data-item">
						<text class="data-value">{{ stats.highAlarms }}</text>
						<text class="data-label">高级告警</text>
					</view>
					<view class="data-item">
						<text class="data-value">{{ stats.processedAlarms }}</text>
						<text class="data-label">已处理</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 图表区域 -->
		<view class="chart-section">
			<view class="section-header">
				<text class="section-title">设备状态分布</text>
			</view>
			<view class="chart-container">
				<view v-if="isUsingMockData" class="data-list">
					<view v-for="(item, index) in deviceStatusData" :key="index" class="data-list-item">
						<view class="data-name">{{item.name}}</view>
						<view class="data-bar-container">
							<view class="data-bar" :style="{width: (item.value / stats.totalDevices * 100) + '%'}"></view>
						</view>
						<view class="data-value-text">{{item.value}}台</view>
					</view>
				</view>
				<view v-else class="chart-placeholder">
					<text>设备状态饼图</text>
					<text class="chart-note">此处将展示设备在线/离线/故障的分布比例</text>
				</view>
			</view>
		</view>
		
		<view class="chart-section">
			<view class="section-header">
				<text class="section-title">告警趋势</text>
			</view>
			<view class="chart-container">
				<view v-if="isUsingMockData" class="data-list trend-data">
					<view class="trend-header">
						<view class="trend-label" v-for="(category, index) in alarmTrendData.categories" :key="index">
							{{category}}
						</view>
					</view>
					<view v-for="(series, seriesIndex) in alarmTrendData.series" :key="seriesIndex" class="trend-row">
						<view class="trend-series-name">{{series.name}}</view>
						<view class="trend-values">
							<view v-for="(value, index) in series.data" :key="index" class="trend-value">
								{{value}}
							</view>
						</view>
					</view>
				</view>
				<view v-else class="chart-placeholder">
					<text>告警趋势折线图</text>
					<text class="chart-note">此处将展示一段时间内的告警数量变化趋势</text>
				</view>
			</view>
		</view>
		
		<view class="chart-section">
			<view class="section-header">
				<text class="section-title">设备类型分布</text>
			</view>
			<view class="chart-container">
				<view v-if="isUsingMockData" class="data-list">
					<view v-for="(item, index) in deviceTypeData" :key="index" class="data-list-item">
						<view class="data-name">{{item.name}}</view>
						<view class="data-bar-container">
							<view class="data-bar type-bar" :style="{width: (item.value / 135 * 100) + '%'}"></view>
						</view>
						<view class="data-value-text">{{item.value}}台</view>
					</view>
				</view>
				<view v-else class="chart-placeholder">
					<text>设备类型饼图</text>
					<text class="chart-note">此处将展示不同类型设备的数量占比</text>
				</view>
			</view>
		</view>
		
		<!-- 日期选择器弹窗 -->
		<uni-popup ref="datePopup" type="bottom" :mask-click="true" @change="popupChange">
			<view class="popup-content">
				<view class="popup-header">
					<text class="cancel" @click="showDatePicker = false">取消</text>
					<text class="title">选择日期范围</text>
					<text class="confirm" @click="confirmDateRange">确定</text>
				</view>
				<view class="date-picker-container">
					<picker-view :indicator-style="indicatorStyle" class="date-picker">
						<picker-view-column>
							<view class="picker-item" v-for="(year, index) in years" :key="index">{{ year }}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(month, index) in months" :key="index">{{ month }}月</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(day, index) in days" :key="index">{{ day }}日</view>
						</picker-view-column>
					</picker-view>
					<view class="date-separator">至</view>
					<picker-view :indicator-style="indicatorStyle" class="date-picker">
						<picker-view-column>
							<view class="picker-item" v-for="(year, index) in years" :key="index">{{ year }}年</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(month, index) in months" :key="index">{{ month }}月</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="(day, index) in days" :key="index">{{ day }}日</view>
						</picker-view-column>
					</picker-view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import api from '../common/api.index.js';

// 定义图表变量
let deviceStatusChart = null;
let alarmTrendChart = null;
let deviceTypeChart = null;

export default {
	data() {
		const currentDate = new Date();
		const years = Array.from({length: 10}, (_, i) => currentDate.getFullYear() - 5 + i);
		const months = Array.from({length: 12}, (_, i) => i + 1);
		const days = Array.from({length: 31}, (_, i) => i + 1);
		
		return {
			timeRanges: [
				{ id: 'today', name: '今日' },
				{ id: 'week', name: '本周' },
				{ id: 'month', name: '本月' },
				{ id: 'year', name: '本年' },
				{ id: 'custom', name: '自定义' }
			],
			activeTimeRange: 'today',
			showDatePicker: false,
			startDate: '',
			endDate: '',
			years,
			months,
			days,
			indicatorStyle: 'height: 50px;',
			stats: {
				totalDevices: 0,
				onlineDevices: 0,
				offlineDevices: 0,
				totalAlarms: 0,
				highAlarms: 0,
				processedAlarms: 0
			},
			deviceStatusData: [],
			alarmTrendData: {
				categories: [],
				series: []
			},
			deviceTypeData: [],
			isLoading: false,
			// 添加模拟数据标志
			isUsingMockData: true
		}
	},
	computed: {
		timeRangeText() {
			if (this.activeTimeRange === 'custom' && this.startDate && this.endDate) {
				return `${this.startDate} 至 ${this.endDate}`;
			} else {
				const range = this.timeRanges.find(r => r.id === this.activeTimeRange);
				return range ? range.name : '今日';
			}
		}
	},
	onLoad() {
		this.loadAllStatistics();
	},
	methods: {
		changeTimeRange(rangeId) {
			if (this.activeTimeRange === rangeId) return;
			
			this.activeTimeRange = rangeId;
			
			if (rangeId === 'custom') {
				this.showDatePicker = true;
			} else {
				this.loadAllStatistics();
			}
		},
		
		async loadAllStatistics() {
			this.isLoading = true;
			try {
				if (this.isUsingMockData) {
					// 使用模拟数据
					this.loadMockData();
				} else {
					await Promise.all([
						this.loadDeviceStats(),
						this.loadAlarmStats(),
						this.loadDeviceStatusDistribution(),
						this.loadAlarmTrend(),
						this.loadDeviceTypeDistribution()
					]);
				}
			} catch (error) {
				console.error('加载统计数据失败', error);
				uni.showToast({
					title: '加载数据失败',
					icon: 'none'
				});
				// 如果API调用失败，使用模拟数据
				this.loadMockData();
			} finally {
				this.isLoading = false;
			}
		},
		
		async loadDeviceStats() {
			try {
				const response = await api.statsApi.getDeviceStats(this.getTimeParams());
				if (response.data && response.data.code === 0) {
					const data = response.data.data;
					this.stats.totalDevices = data.totalDevices || 0;
					this.stats.onlineDevices = data.onlineDevices || 0;
					this.stats.offlineDevices = data.offlineDevices || 0;
				}
			} catch (error) {
				console.error('加载设备统计数据失败', error);
			}
		},
		
		async loadAlarmStats() {
			try {
				const response = await api.statsApi.getAlarmStats(this.getTimeParams());
				if (response.data && response.data.code === 0) {
					const data = response.data.data;
					this.stats.totalAlarms = data.totalAlarms || 0;
					this.stats.highAlarms = data.highAlarms || 0;
					this.stats.processedAlarms = data.processedAlarms || 0;
				}
			} catch (error) {
				console.error('加载告警统计数据失败', error);
			}
		},
		
		async loadDeviceStatusDistribution() {
			try {
				const response = await api.statsApi.getDeviceStatusDistribution(this.getTimeParams());
				if (response.data && response.data.code === 0) {
					this.deviceStatusData = response.data.data || [];
					this.$nextTick(() => {
						this.initDeviceStatusChart();
					});
				}
			} catch (error) {
				console.error('加载设备状态分布数据失败', error);
			}
		},
		
		async loadAlarmTrend() {
			try {
				const response = await api.statsApi.getAlarmTrend(this.getTimeParams());
				if (response.data && response.data.code === 0) {
					const data = response.data.data || {};
					this.alarmTrendData.categories = data.categories || [];
					this.alarmTrendData.series = data.series || [];
					this.$nextTick(() => {
						this.initAlarmTrendChart();
					});
				}
			} catch (error) {
				console.error('加载告警趋势数据失败', error);
			}
		},
		
		async loadDeviceTypeDistribution() {
			try {
				const response = await api.statsApi.getDeviceTypeDistribution(this.getTimeParams());
				if (response.data && response.data.code === 0) {
					this.deviceTypeData = response.data.data || [];
					this.$nextTick(() => {
						this.initDeviceTypeChart();
					});
				}
			} catch (error) {
				console.error('加载设备类型分布数据失败', error);
			}
		},
		
		getTimeParams() {
			if (this.activeTimeRange === 'custom') {
				return {
					startDate: this.startDate,
					endDate: this.endDate
				};
			} else {
				return { timeRange: this.activeTimeRange };
			}
		},
		
		confirmDateRange() {
			if (!this.startDate || !this.endDate) {
				uni.showToast({
					title: '请选择开始和结束日期',
					icon: 'none'
				});
				return;
			}
			
			this.showDatePicker = false;
			this.loadAllStatistics();
		},
		
		cancelDateRange() {
			this.showDatePicker = false;
			if (!this.startDate || !this.endDate) {
				this.activeTimeRange = 'today';
			}
		},
		
		setStartDate(e) {
			this.startDate = e.detail.value;
		},
		
		setEndDate(e) {
			this.endDate = e.detail.value;
		},
		
		initDeviceStatusChart() {
			// 简单文本展示代替图表
			console.log('初始化设备状态图表');
			// 无需实际初始化图表，因为我们会使用文本展示
		},
		
		initAlarmTrendChart() {
			// 简单文本展示代替图表
			console.log('初始化告警趋势图表');
			// 无需实际初始化图表，因为我们会使用文本展示
		},
		
		initDeviceTypeChart() {
			// 简单文本展示代替图表
			console.log('初始化设备类型图表');
			// 无需实际初始化图表，因为我们会使用文本展示
		},
		
		touchHandler(e, chartType) {
			// 简化处理，无需实际操作
			console.log('图表交互', chartType);
		},
		
		popupChange(e) {
			if (!e.show) {
				this.showDatePicker = false;
			}
		},
		
		// 加载模拟数据
		loadMockData() {
			// 设备统计模拟数据
			this.stats.totalDevices = 135;
			this.stats.onlineDevices = 112;
			this.stats.offlineDevices = 23;
			
			// 告警统计模拟数据
			this.stats.totalAlarms = 48;
			this.stats.highAlarms = 12;
			this.stats.processedAlarms = 35;
			
			// 设备状态分布模拟数据
			this.deviceStatusData = [
				{ name: '在线', value: 112 },
				{ name: '离线', value: 18 },
				{ name: '故障', value: 5 }
			];
			
			// 告警趋势模拟数据
			this.alarmTrendData = {
				categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				series: [
					{
						name: '一般告警',
						data: [5, 8, 3, 6, 4, 2, 0]
					},
					{
						name: '严重告警',
						data: [2, 3, 1, 4, 2, 0, 0]
					}
				]
			};
			
			// 设备类型分布模拟数据
			this.deviceTypeData = [
				{ name: '照明设备', value: 45 },
				{ name: '空调设备', value: 30 },
				{ name: '安防设备', value: 25 },
				{ name: '传感器', value: 20 },
				{ name: '其他设备', value: 15 }
			];
		}
	}
}
</script>

<style>
.container {
	padding: 30rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

/* 头部样式 */
.header {
	margin-bottom: 30rpx;
}

.title {
	font-size: 40rpx;
	font-weight: bold;
	color: #333;
}

/* 筛选栏样式 */
.filter-bar {
	display: flex;
	justify-content: space-between;
	margin-bottom: 30rpx;
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.time-filter {
	display: flex;
}

.time-item {
	padding: 10rpx 30rpx;
	border-radius: 8rpx;
	margin-right: 10rpx;
}

.time-item.active {
	background-color: #007AFF;
}

.time-item.active text {
	color: #fff;
}

.time-item text {
	font-size: 28rpx;
	color: #333;
}

.custom-date {
	display: flex;
	align-items: center;
}

.custom-date text {
	font-size: 28rpx;
	color: #333;
}

.date-icon {
	font-size: 20rpx;
	margin-left: 10rpx;
}

/* 数据卡片样式 */
.data-cards {
	display: flex;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.data-card {
	width: 48%;
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.card-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.card-content {
	display: flex;
	justify-content: space-between;
}

.data-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.data-value {
	font-size: 36rpx;
	font-weight: bold;
	color: #007AFF;
	margin-bottom: 10rpx;
}

.data-label {
	font-size: 24rpx;
	color: #666;
}

/* 图表区域样式 */
.chart-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
	padding: 10rpx 0;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.chart-container {
	height: 400rpx;
}

.chart-placeholder {
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	border: 1px dashed #ccc;
	border-radius: 8rpx;
}

.chart-placeholder text {
	font-size: 30rpx;
	color: #999;
}

.chart-note {
	font-size: 24rpx;
	margin-top: 20rpx;
}

/* 日期选择器弹窗样式 */
.popup-content {
	background-color: #fff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
	padding-bottom: 50rpx;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1px solid #f0f0f0;
}

.popup-header .title {
	font-size: 32rpx;
	font-weight: bold;
}

.cancel, .confirm {
	font-size: 28rpx;
}

.cancel {
	color: #999;
}

.confirm {
	color: #007AFF;
}

.date-picker-container {
	display: flex;
	align-items: center;
	padding: 20rpx;
}

.date-picker {
	flex: 1;
	height: 400rpx;
}

.date-separator {
	padding: 0 20rpx;
	color: #999;
}

.picker-item {
	line-height: 50px;
	text-align: center;
}

.data-list {
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.data-list-item {
	display: flex;
	align-items: center;
}

.data-name {
	flex: 1;
}

.data-bar-container {
	width: 200rpx;
	height: 20rpx;
	background-color: #f0f0f0;
	border-radius: 10rpx;
	margin: 0 20rpx;
	overflow: hidden;
}

.data-bar {
	height: 100%;
	background-color: #007AFF;
}

.data-value-text {
	flex: 1;
	text-align: right;
}

.trend-data {
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.trend-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.trend-label {
	padding: 10rpx;
	background-color: #f0f0f0;
	border-radius: 8rpx;
}

.trend-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.trend-series-name {
	flex: 1;
}

.trend-values {
	display: flex;
	justify-content: space-between;
}

.trend-value {
	padding: 10rpx;
}

.type-bar {
	background-color: #007AFF;
}
</style>